<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/3/5
 * Time: 12:59
 */

namespace iBrand\Shop\Backend\Listeners;

use DB;
use iBrand\Shop\Core\Models\ClerkAdminRelation;
use Encore\Admin\Auth\Database\Administrator as AdminUser;
use Illuminate\Support\Facades\Log;

class onCreateClerkListener
{

    public function onCreateClerk($clerk)
    {
        $relation = ClerkAdminRelation::where('clerk_id', $clerk->id)->first();

        if ($relation AND $clerk->is_clerk_owner == 0 AND $admin = AdminUser::find($relation->admin_id)) {
            $relation->delete();
            $admin->delete();
        }

        if (!$relation AND $clerk->is_clerk_owner) {

            $AdminUser = new AdminUser;

            $AdminUser->mobile = $clerk->mobile;

            $AdminUser->username = $clerk->mobile;

            $AdminUser->name = $clerk->mobile;

            $AdminUser->password = $clerk->password;

            $AdminUser->save();

            ClerkAdminRelation::create(['admin_id' => $AdminUser->id, 'clerk_id' => $clerk->id]);

            DB::table(config('admin.database.role_users_table'))->insert(['user_id' => $AdminUser->id, 'role_id' => 1]);

        }
    }

    public function subscribe($events)
    {
        $events->listen(
            'on.shop.create.clerk',
            'iBrand\Shop\Backend\Listeners\onCreateClerkListener@onCreateClerk'
        );
    }
}